import 'package:flutter/material.dart';
import '../style/utils/responsive.dart';
import 'responsive_layout.dart';

/// 应用主页响应式布局
/// 实现移动端、平板端、桌面端的不同布局结构
class ResponsiveAppLayout extends StatelessWidget {
  /// 主要内容区域
  final Widget mainContent;

  /// 左侧边栏内容（桌面端）
  final Widget? leftSidebar;

  /// 右侧边栏内容（桌面端、AI分析等）
  final Widget? rightSidebar;

  /// 应用栏
  final PreferredSizeWidget? appBar;

  /// 底部导航栏（移动端）
  final Widget? bottomNavigationBar;

  /// 浮动操作按钮
  final Widget? floatingActionButton;

  /// 抽屉菜单（移动端）
  final Widget? drawer;

  /// 左侧边栏宽度
  final double? leftSidebarWidth;

  /// 右侧边栏宽度
  final double? rightSidebarWidth;

  /// 背景颜色
  final Color? backgroundColor;

  const ResponsiveAppLayout({
    Key? key,
    required this.mainContent,
    this.leftSidebar,
    this.rightSidebar,
    this.appBar,
    this.bottomNavigationBar,
    this.floatingActionButton,
    this.drawer,
    this.leftSidebarWidth,
    this.rightSidebarWidth,
    this.backgroundColor,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ResponsiveLayout(
      mobile: _buildMobileLayout(context),
      tablet: _buildTabletLayout(context),
      desktop: _buildDesktopLayout(context),
      largeDesktop: _buildLargeDesktopLayout(context),
    );
  }

  /// 移动端布局：单栏 + 底部导航
  Widget _buildMobileLayout(BuildContext context) {
    return Scaffold(
      appBar: appBar,
      body: mainContent,
      drawer: drawer,
      bottomNavigationBar: bottomNavigationBar,
      floatingActionButton: floatingActionButton,
      backgroundColor: backgroundColor,
    );
  }

  /// 平板端布局：根据方向选择布局
  Widget _buildTabletLayout(BuildContext context) {
    final isLandscape = UIResponsive.isLandscape(context);

    if (isLandscape && leftSidebar != null) {
      // 横屏：双栏布局
      return _buildTwoColumnLayout(context);
    } else {
      // 竖屏：单栏布局（类似移动端）
      return _buildMobileLayout(context);
    }
  }

  /// 桌面端布局：三栏布局
  Widget _buildDesktopLayout(BuildContext context) {
    return _buildThreeColumnLayout(context);
  }

  /// 大屏桌面端布局：三栏布局（更宽的间距）
  Widget _buildLargeDesktopLayout(BuildContext context) {
    return _buildThreeColumnLayout(context, isLargeScreen: true);
  }

  /// 双栏布局（平板横屏）
  Widget _buildTwoColumnLayout(BuildContext context) {
    final effectiveLeftWidth = leftSidebarWidth ?? 320.0;

    return Scaffold(
      appBar: appBar,
      backgroundColor: backgroundColor,
      floatingActionButton: floatingActionButton,
      body: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 左侧边栏
          if (leftSidebar != null)
            Container(
              width: effectiveLeftWidth,
              decoration: BoxDecoration(
                color: Theme.of(context).cardColor,
                border: Border(
                  right: BorderSide(
                    color: Theme.of(context).dividerColor,
                    width: 0.5,
                  ),
                ),
              ),
              child: leftSidebar!,
            ),

          // 主内容区域
          Expanded(
            child: mainContent,
          ),
        ],
      ),
    );
  }

  /// 三栏布局（桌面端）
  Widget _buildThreeColumnLayout(BuildContext context,
      {bool isLargeScreen = false}) {
    final effectiveLeftWidth =
        leftSidebarWidth ?? (isLargeScreen ? 360.0 : 320.0);
    final effectiveRightWidth =
        rightSidebarWidth ?? (isLargeScreen ? 400.0 : 360.0);

    return Scaffold(
      appBar: appBar,
      backgroundColor: backgroundColor,
      floatingActionButton: floatingActionButton,
      body: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 左侧边栏
          if (leftSidebar != null)
            Container(
              width: effectiveLeftWidth,
              decoration: BoxDecoration(
                color: Theme.of(context).cardColor,
                border: Border(
                  right: BorderSide(
                    color: Theme.of(context).dividerColor,
                    width: 0.5,
                  ),
                ),
              ),
              child: leftSidebar!,
            ),

          // 主内容区域
          Expanded(
            child: mainContent,
          ),

          // 右侧边栏
          if (rightSidebar != null)
            Container(
              width: effectiveRightWidth,
              decoration: BoxDecoration(
                color: Theme.of(context).cardColor,
                border: Border(
                  left: BorderSide(
                    color: Theme.of(context).dividerColor,
                    width: 0.5,
                  ),
                ),
              ),
              child: rightSidebar!,
            ),
        ],
      ),
    );
  }
}

/// 详情页响应式布局
/// 专门用于内容详情页面的布局结构
class ResponsiveDetailLayout extends StatelessWidget {
  /// 主要内容
  final Widget content;

  /// AI分析侧边栏内容
  final Widget? aiAnalysisSidebar;

  /// 应用栏
  final PreferredSizeWidget? appBar;

  /// AI分析按钮点击回调
  final VoidCallback? onAIAnalysisToggle;

  /// AI分析是否显示
  final bool showAIAnalysis;

  /// AI分析侧边栏宽度
  final double? aiSidebarWidth;

  /// 背景颜色
  final Color? backgroundColor;

  const ResponsiveDetailLayout({
    Key? key,
    required this.content,
    this.aiAnalysisSidebar,
    this.appBar,
    this.onAIAnalysisToggle,
    this.showAIAnalysis = false,
    this.aiSidebarWidth,
    this.backgroundColor,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ResponsiveLayout(
      mobile: _buildMobileLayout(context),
      tablet: _buildTabletLayout(context),
      desktop: _buildDesktopLayout(context),
    );
  }

  /// 移动端布局：主内容 + 底部抽屉
  Widget _buildMobileLayout(BuildContext context) {
    return Scaffold(
      appBar: appBar,
      backgroundColor: backgroundColor,
      body: Stack(
        children: [
          // 主内容
          content,

          // AI分析底部抽屉
          if (showAIAnalysis && aiAnalysisSidebar != null)
            _buildMobileAIDrawer(context),
        ],
      ),
    );
  }

  /// 平板端布局：根据方向选择
  Widget _buildTabletLayout(BuildContext context) {
    final isLandscape = UIResponsive.isLandscape(context);

    if (isLandscape && aiAnalysisSidebar != null) {
      // 横屏：侧边栏布局
      return _buildSidebarLayout(context, sidebarWidth: 300.0);
    } else {
      // 竖屏：底部抽屉布局
      return _buildMobileLayout(context);
    }
  }

  /// 桌面端布局：固定右侧边栏
  Widget _buildDesktopLayout(BuildContext context) {
    return _buildSidebarLayout(context);
  }

  /// 侧边栏布局（桌面端和平板横屏）
  Widget _buildSidebarLayout(BuildContext context, {double? sidebarWidth}) {
    final effectiveWidth = sidebarWidth ?? aiSidebarWidth ?? 400.0;

    return Scaffold(
      appBar: appBar,
      backgroundColor: backgroundColor,
      body: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 主内容区域
          Expanded(
            child: content,
          ),

          // AI分析侧边栏
          if (showAIAnalysis && aiAnalysisSidebar != null)
            AnimatedContainer(
              duration: const Duration(milliseconds: 300),
              width: effectiveWidth,
              decoration: BoxDecoration(
                color: Theme.of(context).cardColor,
                border: Border(
                  left: BorderSide(
                    color: Theme.of(context).dividerColor,
                    width: 0.5,
                  ),
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    offset: const Offset(-2, 0),
                    blurRadius: 8,
                  ),
                ],
              ),
              child: aiAnalysisSidebar!,
            ),
        ],
      ),
    );
  }

  /// 移动端AI分析底部抽屉
  Widget _buildMobileAIDrawer(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final drawerHeight = screenHeight * 0.7; // 占屏幕70%高度

    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        height: drawerHeight,
        decoration: BoxDecoration(
          color: Theme.of(context).cardColor,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.3),
              offset: const Offset(0, -4),
              blurRadius: 16,
            ),
          ],
        ),
        child: Column(
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 12),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Theme.of(context).dividerColor,
                borderRadius: BorderRadius.circular(2),
              ),
            ),

            // AI分析内容
            Expanded(
              child: aiAnalysisSidebar!,
            ),
          ],
        ),
      ),
    );
  }
}

/// 网格式内容布局
/// 自动适应不同屏幕尺寸的网格布局
class ResponsiveGridLayout extends StatelessWidget {
  final List<Widget> items;
  final Widget? header;
  final Widget? footer;
  final EdgeInsets? padding;
  final double itemSpacing;
  final double lineSpacing;

  /// 移动端列数
  final int mobileColumns;

  /// 平板端列数
  final int tabletColumns;

  /// 桌面端列数
  final int desktopColumns;

  /// 大屏桌面端列数
  final int largeDesktopColumns;

  /// 子项宽高比
  final double childAspectRatio;

  const ResponsiveGridLayout({
    Key? key,
    required this.items,
    this.header,
    this.footer,
    this.padding,
    this.itemSpacing = 16.0,
    this.lineSpacing = 16.0,
    this.mobileColumns = 1,
    this.tabletColumns = 2,
    this.desktopColumns = 3,
    this.largeDesktopColumns = 4,
    this.childAspectRatio = 1.0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ResponsiveContainer(
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 头部内容
          if (header != null) ...[
            header!,
            SizedBox(height: lineSpacing),
          ],

          // 网格内容
          ResponsiveGrid(
            mobileColumns: mobileColumns,
            tabletColumns: tabletColumns,
            desktopColumns: desktopColumns,
            largeDesktopColumns: largeDesktopColumns,
            crossAxisSpacing: itemSpacing,
            mainAxisSpacing: lineSpacing,
            childAspectRatio: childAspectRatio,
            children: items,
          ),

          // 底部内容
          if (footer != null) ...[
            SizedBox(height: lineSpacing),
            footer!,
          ],
        ],
      ),
    );
  }
}

/// 响应式列表布局
/// 自动适应不同屏幕尺寸的列表展示方式
class ResponsiveListLayout extends StatelessWidget {
  final List<Widget> items;
  final Widget? header;
  final Widget? footer;
  final EdgeInsets? padding;
  final double itemSpacing;

  /// 是否在桌面端使用卡片式布局
  final bool useCardsOnDesktop;

  /// 桌面端每行项目数（使用卡片式布局时）
  final int desktopItemsPerRow;

  const ResponsiveListLayout({
    Key? key,
    required this.items,
    this.header,
    this.footer,
    this.padding,
    this.itemSpacing = 8.0,
    this.useCardsOnDesktop = false,
    this.desktopItemsPerRow = 2,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ResponsiveLayout(
      mobile: _buildMobileList(context),
      tablet: _buildTabletList(context),
      desktop: _buildDesktopList(context),
    );
  }

  Widget _buildMobileList(BuildContext context) {
    return _buildBasicList(context);
  }

  Widget _buildTabletList(BuildContext context) {
    return _buildBasicList(context);
  }

  Widget _buildDesktopList(BuildContext context) {
    if (useCardsOnDesktop) {
      return _buildGridList(context);
    }
    return _buildBasicList(context);
  }

  Widget _buildBasicList(BuildContext context) {
    return ResponsiveContainer(
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (header != null) header!,
          ...items
              .map((item) => Padding(
                    padding: EdgeInsets.only(bottom: itemSpacing),
                    child: item,
                  ))
              .toList(),
          if (footer != null) footer!,
        ],
      ),
    );
  }

  Widget _buildGridList(BuildContext context) {
    return ResponsiveContainer(
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (header != null) ...[
            header!,
            SizedBox(height: itemSpacing),
          ],

          // 网格布局
          ResponsiveGrid(
            desktopColumns: desktopItemsPerRow,
            crossAxisSpacing: itemSpacing,
            mainAxisSpacing: itemSpacing,
            children: items,
          ),

          if (footer != null) ...[
            SizedBox(height: itemSpacing),
            footer!,
          ],
        ],
      ),
    );
  }
}

/// 响应式对话框
/// 自动适应不同屏幕尺寸的对话框样式
class ResponsiveDialog extends StatelessWidget {
  final Widget child;
  final String? title;
  final EdgeInsets? padding;
  final double? width;
  final double? height;
  final bool? barrierDismissible;

  const ResponsiveDialog({
    Key? key,
    required this.child,
    this.title,
    this.padding,
    this.width,
    this.height,
    this.barrierDismissible,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final dialogType = UIResponsive.getDialogType(context);

    switch (dialogType) {
      case DialogType.fullscreen:
        return _buildFullscreenDialog(context);
      case DialogType.center:
        return _buildCenterDialog(context);
    }
  }

  Widget _buildFullscreenDialog(BuildContext context) {
    return Scaffold(
      appBar: title != null
          ? AppBar(
              title: Text(title!),
              centerTitle: true,
            )
          : null,
      body: Padding(
        padding: padding ?? const EdgeInsets.all(16),
        child: child,
      ),
    );
  }

  Widget _buildCenterDialog(BuildContext context) {
    return AlertDialog(
      title: title != null ? Text(title!) : null,
      content: SizedBox(
        width: width ?? 400,
        height: height,
        child: Padding(
          padding: padding ?? EdgeInsets.zero,
          child: child,
        ),
      ),
    );
  }

  /// 显示响应式对话框
  static Future<T?> show<T>({
    required BuildContext context,
    required Widget child,
    String? title,
    EdgeInsets? padding,
    double? width,
    double? height,
    bool barrierDismissible = true,
  }) {
    final dialog = ResponsiveDialog(
      title: title,
      padding: padding,
      width: width,
      height: height,
      barrierDismissible: barrierDismissible,
      child: child,
    );

    final dialogType = UIResponsive.getDialogType(context);

    if (dialogType == DialogType.fullscreen) {
      return Navigator.of(context).push<T>(
        MaterialPageRoute(
          builder: (context) => dialog,
          fullscreenDialog: true,
        ),
      );
    } else {
      return showDialog<T>(
        context: context,
        barrierDismissible: barrierDismissible,
        builder: (context) => dialog,
      );
    }
  }
}
